require("sys")
local uartid=2
local dcom = {}
dcom.buff = zbuff.create(1024)
local function ComInit()
    local result = uart.setup(
        uartid,--串口id
        115200,--波特率
        8,--数据位
        1--停止位
    )    
    uart.on(uartid, "receive", function(id, len)
        local len = uart.rx(id, dcom.buff)
        --deal data buff --> string
        if dcom.buff:used() > 0 then
            local cmd = dcom.buff:toStr(0, len)
            log.info("com recved:",len, cmd)
            dcom.buff:del()
            dcom.buff:seek(0)
            local msg,ret,err = json.decode(cmd)
            log.info("decode",msg,ret,err)
            if msg ~= nil then
                sys.publish("ddn_event", {src = "dcom",evt = "COMMAND", dat = msg})
                -- uart.write(id,cmd)
            end
        end      
    end)      
end

local function ComMain()
    log.info("--------------------ComMain--------------------------",uart.exist(0),uart.exist(1),uart.exist(2))

    ComInit()
    while true do
        local ret,dat = sys.waitUntil("ddn_event")
        if(ret==true) then
            if (dat.src == "dsec" and dat.evt == "HEART") then
                log.info("------dcom 心跳到来------")
                local llll = uart.write(uartid,string.format("{heart:%05d}\r\n",dat.dat.heart))
                log.info("com write len:",llll)
            end            
        end
    end
end

local function Init()
    sys.taskInit(ComMain)
end
dcom.Init = Init
return dcom

